package com.pbase.tools;

import org.jetbrains.annotations.NotNull;

import java.util.concurrent.TimeUnit;

import androidx.annotation.NonNull;
import androidx.lifecycle.DefaultLifecycleObserver;
import androidx.lifecycle.LifecycleOwner;
import androidx.lifecycle.MutableLiveData;
import io.reactivex.rxjava3.android.schedulers.AndroidSchedulers;
import io.reactivex.rxjava3.core.Flowable;
import io.reactivex.rxjava3.disposables.Disposable;

/**
 * User: psn
 * Date: 2021/6/24
 * 倒计时工具
 */
public class TimeCountDown implements DefaultLifecycleObserver {
    private Disposable disposable;
    private boolean isAutoReStart;//重进界面是否自动重启计时
    private boolean isFirst;
    private MutableLiveData<Integer> timeFlag;
    private CountDownTimeListener listener;

    public void start(int time, CountDownTimeListener listener) {
        start(time, null, listener, false);
    }

    public void start(int time, MutableLiveData<Integer> timeFlag, CountDownTimeListener listener) {
        start(time, timeFlag, listener, false);
    }

    public void start(int time, CountDownTimeListener listener, boolean isAutoReStart) {
        start(time, null, listener, isAutoReStart);
    }

    public void start(int time, MutableLiveData<Integer> timeFlag, CountDownTimeListener listener
            , boolean isAutoReStart) {
        this.timeFlag = timeFlag;
        this.listener = listener;
        this.isAutoReStart = isAutoReStart;
        isFirst = true;
        disposable =
                Flowable.interval(0, 1, TimeUnit.SECONDS)
                        .observeOn(AndroidSchedulers.mainThread())
                        .subscribe(aLong -> {
                            if (aLong == time) {
                                stop();
                                listener.complete();
                            }
                            timeFlag.setValue((int) (time - aLong));
                        });
    }

    public void stop() {
        if (disposable != null && !disposable.isDisposed()) {
            disposable.dispose();
        }
    }

    @Override
    public void onPause(@NonNull @NotNull LifecycleOwner owner) {
        isFirst = false;
        stop();
    }

    @Override
    public void onResume(@NonNull @NotNull LifecycleOwner owner) {
        if (isAutoReStart && !isFirst) {
            start(timeFlag.getValue(), timeFlag, listener, isAutoReStart);
        }
    }

    @Override
    public void onDestroy(@NonNull @NotNull LifecycleOwner owner) {
        disposable = null;
        isAutoReStart = false;
    }

    public interface CountDownTimeListener {
        void complete();
    }
}
